package sg.edu.nus.iss;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import sg.edu.nus.iss.stockex.*;
import javax.tools.FileObject;

import org.apache.commons.codec.net.QuotedPrintableCodec;


public class StockQuoteUtil {
	public static final String FILE_NAME = "SESPrice";
	public static final String NAME_SEPERATOR = "_";
	public static final String URL_SEPERATOR = "/";
	public static final String SITE_URL = "http://info.sgx.com/webprices.nsf/stkprices";
	public static final String FILE_URL_PART = "/%24File/SESprice.dat";
	/**
	 * @param args
	 */
	
	
	
	public static boolean getFile(String path, String dateStr)
	{
		try {
			
			String fileURL = SITE_URL + URL_SEPERATOR + dateStr + FILE_URL_PART;
			URL url = new URL(fileURL);
			URLConnection conn = url.openConnection();
			InputStream stream = conn.getInputStream();
			FileOutputStream fos = new FileOutputStream(path +  FILE_NAME + NAME_SEPERATOR + dateStr);
			int read = 0;
			byte[] bytes = new byte[1024];
		 
			while ((read = stream.read(bytes)) != -1) {
				fos.write(bytes, 0, read);
			}
		 
			stream.close();
			fos.flush();
			fos.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public static ArrayList<StockQuote> getQuoteList(String dateStr)
	{
		ArrayList<StockQuote> quoteList = new ArrayList<StockQuote>();
		try {
			
			String fileURL = SITE_URL + URL_SEPERATOR + dateStr + FILE_URL_PART;
			
			URL url = new URL(fileURL);
			URLConnection conn = url.openConnection();
			InputStream stream = conn.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
			String quoteData = "";
			StockQuote quote = null;
			while((quoteData = reader.readLine())!="" && quoteData !=null)
			{
				try{
				quote = StockQuote.parseString(quoteData);
				System.out.println(quote);
				if(quote!=null){
					quoteList.add(quote);
				}
				}catch (Exception e) {
					e.printStackTrace();
					// TODO: handle exception
				
				}
			}
				
				
			stream.close();
			reader.close();
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		return quoteList;
	}
	

}
